<template>
  <div class="audioPage">
    <!-- 1.顶部导航栏 -->
    <Nav :data="form" />

    <!-- 2.文字记录/搜索 -->
    <div class="top">
      <h3>文字记录</h3>
      <div class="search">
        <el-input
          v-model="inputValue"
          class="w-50 m-2"
          placeholder="搜索"
          :prefix-icon="Search"
          @input="inputChange"
          :clearable="true"
        >
          <template #suffix>
             <span v-if="inputValue">{{count}}</span>
          </template>
        </el-input>
      </div>
    </div>
    <!-- 3.文字记录信息 -->
    <div class="transcriptionRecord">
      <el-scrollbar height="100%" ref="scrollbarRef">
        <template v-if="list.length>0">
          <div  class="recordinfo" v-for="(item, i) in list" :key="i" :id="'scroll_' + item.id" @wheel="handleScroll">
            <!-- 1.左侧 -->
            <!-- <div class="left">{{ item.userName.slice(-2) }}</div> -->
            <!-- 2.右侧 -->
            <div class="right">
              <!-- 2.1 上层 -->
              <div class="right-top">
                <!-- <span>{{ item.userName }}</span> -->
                <span>说话人</span>
                <span>{{ getHMS(item.startTime) }}</span>
              </div>
              <!-- 2.2 文字转写内容 -->
              <div
                v-html="item.content"
                class="rightContent"
                :class="[
                  currentTimes * 1000 >= item.startTime && currentTimes * 1000 < item.endTime
                    ? 'active'
                    : ''
                ]"
                @click="reversePosition(item)"
              ></div>
            </div>
          </div>
        </template>
        <div v-else style="text-align:center;color:lightgray;margin-top: 10px;">无文字记录</div>
      </el-scrollbar>
    </div>
    <!-- 4. 音频播放 -->
    <AudioBar
      :audioSrc="form.url ? form.url : audioSrc"
      :currentTime="currentTime"
      @currentTimeChangeCallBack="currentTimeChange"
      ref="AudioBarRef"
    ></AudioBar>
  </div>
</template>

<script setup>
import Nav from '@/components/Nav.vue'
import { ref, onMounted, computed,onBeforeUnmount,watch} from 'vue'
import { Search } from '@element-plus/icons-vue'
import { useRoute} from 'vue-router'
const route = useRoute()
import AudioBar from '@/components/AudioBar/AudioBar.vue'
import { request } from '@/utils/server.js'

import audioSrc from '@/assets/1.mp3'

// 接收HomePage.vue 或 MyContent.vue页面的query传参
const form = ref({
  userId:route.query.userId,
  id: route.query.id,
  title: '',
  createdTime: '',
  totalTime: '',
  userName:'',
  url: route.query.url,
  inputValue:route.query.inputValue,
  searchKeys:route.query.searchKeys|| [],
  from:route.query.from
})

// 0.----获取最近列表接口,根据列表id,获取文件信息-----
const getContentList = () => {
  // debugger
  request
    .get(
      '/sweet-api/video/'+form.value.id
    )
    .then((res) => {
      // debugger
      // console.log("根据列表id,获取文件信息成功",res.data);
      if (res.data.code == 1) {
        let list = res.data.data 
        
        form.value.title=list.title
        form.value.createdTime= list.createdTime
        form.value.totalTime= list.totalTime
        form.value.userName=list.userName    
      }
    })
    .catch((error) => {
      console.log('根据列表id,获取文件信息失败', error)
      ElMessage({
        message: error || '根据列表id,获取文件信息失败',
        type: 'error'
      })
    })
    .finally(() => {
      
    })
}

// 接收子组件传递的数据
const currentTimes = ref(-1)
const getHighLight = () => {
  let res = -1
  for (let i = 0; i < list.value.length; i++) {
    // debugger
    if (
      list.value[i].startTime <= currentTimes.value * 1000 &&
      list.value[i].endTime > currentTimes.value * 1000
    ) {
      // console.log(currentTimes.value,list.value[i].startTime,list.value[i].endTime)
      res = i
      break
    }
  }
  return res
}
const scrollbarRef = ref()
const iswheel=ref(false)
const currentTimeChange = (v) => {
  // console.log('接收子组件传递', v)
  //  currentTime.value=v
  //  console.log('接收子组件传递',currentTime.value*1000 )
  currentTimes.value = v.audioTime
  let index = getHighLight()
  // console.log('index', index)
  // debugger
  if (index > -1) {
    // debugger
    // 添加滚轮事件监听器,取消滚动到可视区
    if(!iswheel.value){
      document.getElementById('scroll_' + list.value[index].id).scrollIntoView({ behavior: 'smooth',block: 'nearest'})
    }
  }
}

const wheelFn=function(event) {
  iswheel.value=true
  window.removeEventListener("wheel",wheelFn) 
}
window.addEventListener('wheel', wheelFn)




// 1.----会议记录（转文字）接口-----
const isFinished=ref(false)
const getConferenceList = () => {
  request
    .get('/sweet-api/conference/list/' + route.query.id)
    .then((res) => {
      // debugger
      // console.log("会议记录获取成功",res.data);
      if (res.data.code == 1) {
        originList.value = res.data.data
      }
    })
    .catch((error) => {
      console.log('会议记录获取失败', error)
    })
    .finally(()=>{
       isFinished.value=true
    })
}
// 2.----添加到主页接口-----
const addToMainPage = (id) => {
  request
    .get('/sweet-api/play/video/click/' + id)
    .then((res) => {
      // debugger
      if (res.data.code == 1) {
        console.log('添加到主页成功', res.data)
      }
    })
    .catch((error) => {
      console.log('添加到主页失败', error)
    })
}

// 3.----文章摘要接口-----
const getSummery = () => {
  request
    .get('/sweet-api/summery/query/' + route.query.id)
    .then((res) => {
      // debugger
      // console.log("获取文章摘要成功",res.data);
      if (res.data.code == 1) {
        
      }
    })
    .catch((error) => {
      console.log('获取文章摘要失败', error)
    })
}

onMounted(() => {
  if(route.query.from=='recently'){
    // 根据列表id,获取文件信息
    getContentList()
  }else{
    //根据列表id,获取文件信息
    getContentList()
  }

  // 添加到主页接口
  addToMainPage(route.query.id)
  // 会议记录（转文字）接口
  getConferenceList()

  //文章摘要接口 
  // getSummery()
})
onBeforeUnmount(()=>{
  window.removeEventListener("wheel",wheelFn)
})

// 2.搜索框
const inputValue = ref(form.value.inputValue)
// 防抖
function debounce(func, wait, immediate) {
  let timeout
  return function () {
    let context = this
    let args = arguments
    if (timeout) {
      clearTimeout(timeout)
    }
    if (immediate) {
      let callNow = !timeout
      timeout = setTimeout(() => {
        timeout = null
      }, wait)
      if (callNow) {
        typeof func === 'function' && func.apply(context, args)
      }
    } else {
      timeout = setTimeout(() => {
        typeof func === 'function' && func.apply(context, args)
      }, wait)
    }
  }
}
// 搜索框输入内容变化，搜索
const inputChangeFn = () => {
  console.log(inputValue.value)
  count.value=0
  // debugger
  if (inputValue.value != '') {
     
  }else{

  }
}
const inputChange = debounce(inputChangeFn, 500, false)

//3. 文字记录
const originList = ref([
  
])

const count =ref(0)

const list = computed(() => {
  // debugger
  let arr = []
  let fenci=[]
  if (inputValue.value && isFinished.value) {
    //修改
    if(form.value.searchKeys && form.value.searchKeys.length>0){
       fenci=form.value.searchKeys
       form.value.searchKeys=[]
       
    }else{
      fenci.push(inputValue.value)
      
    }
    
    for (let i = 0; i < originList.value.length; i++) {
      let item = JSON.parse(JSON.stringify(originList.value[i]))
      for(let j=0;j<fenci.length;j++){
        let fenciitem=fenci[j]
        if (item.content.indexOf(fenciitem) > -1) {
        
          let reg = new RegExp(fenciitem, 'g')

          item.content = item.content.replace(
            reg,
            `<span style='background-color: #fff67a;
            color:#333;' class="search">${fenciitem}</span>`
          )

          let matches=item.content.match(reg);
          
          count.value=count.value+(matches ? matches.length : 0)
        }

      }
      
      arr.push(item)
    }
  } else {
    arr = [...originList.value]
  }

  return arr
})
// 根据毫秒数转换成对应的时分秒
const getHMS = (times) => {
  let time = times / 1000
  const hour = parseInt(time / 3600) < 10 ? '0' + parseInt(time / 3600) : parseInt(time / 3600)
  const min =
    parseInt((time % 3600) / 60) < 10
      ? '0' + parseInt((time % 3600) / 60)
      : parseInt((time % 3600) / 60)
  const sec =
    parseInt((time % 3600) % 60) < 10
      ? '0' + parseInt((time % 3600) % 60)
      : parseInt((time % 3600) % 60)
  return hour + ':' + min + ':' + sec
}

// 点击文字记录 反向定位视频
const currentTime = ref()
const AudioBarRef = ref()
const reversePosition = (item) => {
  let a = Number((item.startTime / 1000).toFixed(6))
  currentTime.value = a
  currentTimes.value = a

  AudioBarRef.value.startPlayAudio()
  // debugger
}


// watch( AudioBarRef.value,()=>{
//   AudioBarRef.value.onAudioLoadedmetadata()
// })

</script>

<style lang="less" scoped>
.audioPage {
  margin: 0;
  height: 100%;
  display: flex;
  flex-direction: column;
  // 2.2.文字记录/搜索
  .top {
    height: 77px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex: none;
    .search {
      width: 240px;
      height: 34px;
      border-radius: 2px;
      color: rgba(206, 206, 206, 1);
      font-size: 14px;
      text-align: left;
      font-family: Roboto;
    }
  }

  // 3.文字记录信息
  .transcriptionRecord {
    //height: 100%;
    display: flex;
    flex-direction: column;
    flex: 1;
    overflow-y: auto;

    .recordinfo {
      margin-bottom: 10px;
      display: flex;
      justify-content: flex-start;
      //1.左侧
      .left {
        width: 34px;
        height: 34px;
        line-height: 34px;
        border-radius: 50%;
        background: linear-gradient(180deg, rgba(92, 219, 211, 1) 0%, rgba(19, 194, 194, 1) 100%);
        color: rgba(255, 255, 255, 1);
        font-size: 12px;
        margin-right: 8px;
        text-align: center;
        font-family: Microsoft Yahei;
        flex: none;
      }
      // 2.右侧
      .right {
        .right-top {
          & > span {
            width: 28px;
            height: 20px;
            color: rgba(145, 145, 145, 1);
            font-size: 14px;
            text-align: left;
            font-family: PingFangSC-regular;
            margin-right: 4px;
          }
          & > span:nth-child(2) {
            font-size: 12px;
          }
        }
        .rightContent {
          // height: 48px;
          color: rgba(64, 64, 64, 1);
          font-size: 14px;
          text-align: left;
          font-family: SourceHanSansSC-regular;
        }
        .active {
          background-color: #096dd9;
          color: #fff;
        }
      }
    }
  }

  // 4.音频播放
}
</style>
